//
//  ViewController.m
//  ALittleReminder
//
//  Created by George on 11-11-01.
//  
// Changes:
// 2011-11-03: textField now closes the keyboard after return. (George)
// 2011-11-02: Improved the time picker (George)
// 2011-11-01: A working one use alert. Waring: It will only show is the app is hidden/closed.(George)

#import "SetAlertViewController.h"
#import "AlertManagedObject.h"
#import "SetTimeViewController.h"
#import "AppDelegate.h"
#import "ImagePickerControllerDelegate.h"
#import "TextViewController.h"
#import "AudioRecorderViewController.h"

@implementation SetAlertViewController{
    AlertManagedObject * myAlert;
    bool isNew;
    ImagePickerControllerDelegate *imageDelegate;//the image picker doesn't want to hold it for ARC when swiching views, so we will hold it for image picker.
}
@synthesize nameTextField;
@synthesize timeButton;
@synthesize finishButton;
@synthesize addTextButton;
@synthesize takePictureButton;
@synthesize albumPictureButton;


//Must use for init of SetAlertViewController.
//If alert is nil, then create a new alert.
//If alert is not nil, then edit this alert.
- (id)initWithAlert:(AlertManagedObject *)alertOrNil
{
    self = [super initWithNibName:@"SetAlertViewController_iPhone" bundle:nil];
    if (self) {
        if (alertOrNil) {
            myAlert = alertOrNil;
            isNew = NO;
        }else{
            myAlert = [NSEntityDescription insertNewObjectForEntityForName:@"AlertManagedObject" inManagedObjectContext:[[AppDelegate getInstance] managedObjectContext]];
            isNew = YES;
        }
    }
    return self;
}

//Tries to finish editing an alert.
//If there is missing data, then it shows a pop-up window indicating that there is missing input.
//If all the data is complete, then it sets the alert and returns to the main screen.
- (IBAction)doSetAlert:(id)sender {
    
    //Check for missing data
    if (!myAlert.name||[myAlert.name length]<1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please gave me a name." message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    if (!myAlert.date) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please set date and time." message:@"" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    // save alert
    [AppDelegate saveManagedObjects];

    // schedule the alert
    NSLog(@"set alert");
    NSLog(@"%@",myAlert.name);
    NSLog(@"%@",myAlert.date);
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = myAlert.date;
    
    NSString *body;
    if (!myAlert.text) {
        body = myAlert.name;
    }else{
        body = [NSString stringWithFormat:@"%@\n%@",myAlert.name,myAlert.text];
    }
    localNotif.alertBody = body;
    
    localNotif.soundName = @"Apple_Ring.aif";
    localNotif.userInfo = [NSDictionary dictionaryWithObject:[[[myAlert objectID] URIRepresentation]absoluteString] forKey:@"url"];
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    NSLog(@"scheduled");
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidUnload
{
    myAlert = nil;
    imageDelegate = nil;
    [self setNameTextField:nil];
    [self setFinishButton:nil];
    [self setTimeButton:nil];
    [self setTakePictureButton:nil];
    [self setAlbumPictureButton:nil];
    [self setAddTextButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    if (myAlert) {
        //show the name if exists
        if (myAlert.name) {
            nameTextField.text = myAlert.name;
        }else{
            nameTextField.text = @"";
        }
        //show the date if exists
        if (myAlert.date) {
            NSString *time = [myAlert timeToString];
            
            [timeButton setTitle:time forState:UIControlStateNormal];
           
        }else{
            [timeButton setTitle:@"???" forState:UIControlStateNormal];
           
        }
        //show the image if exists
        [myAlert useImage:^(UIImage * image)
        {
            //NSLog(@"use image:%@",image);
                
            [takePictureButton setBackgroundImage:image forState: UIControlStateNormal];
            
            [albumPictureButton setBackgroundImage:image forState: UIControlStateNormal];
            
        }];
        //Show the text if exits
        if (myAlert.text && [myAlert.text length]>0) {
            [addTextButton setTitle:myAlert.text forState:UIControlStateNormal];
            addTextButton.titleLabel.numberOfLines = 5;
            addTextButton.titleLabel.lineBreakMode = UILineBreakModeClip;
            addTextButton.titleLabel.font = [UIFont systemFontOfSize:10];
        }else{
            [addTextButton setTitle:@"Add Text" forState:UIControlStateNormal];
            addTextButton.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
            addTextButton.titleLabel.font = [UIFont boldSystemFontOfSize:22];
        }

    }
    [super viewWillAppear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

- (IBAction)onOpenTime:(id)sender {
    [self textFieldShouldReturn:nameTextField];//hide the keyboard
    SetTimeViewController *openView = [[SetTimeViewController alloc] initWithAlert:myAlert];
    [self presentModalViewController:openView animated:YES];
}

- (IBAction)onTakeAPicture:(id)sender {
    [self textFieldShouldReturn:nameTextField];//hide the keyboard
    imageDelegate = [[ImagePickerControllerDelegate alloc] init];
    imageDelegate.alert = myAlert;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = imageDelegate;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else{
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    [self presentModalViewController:imagePicker animated:YES];
}

- (IBAction)onPictureFromAlbum:(id)sender {
    [self textFieldShouldReturn:nameTextField];//hide the keyboard
    imageDelegate = [[ImagePickerControllerDelegate alloc] init];
    imageDelegate.alert = myAlert;
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = imageDelegate;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:imagePicker animated:YES];
}

- (IBAction)onAddText:(id)sender {
    [self textFieldShouldReturn:nameTextField];//hide the keyboard
    TextViewController *openView = [[TextViewController alloc] initWithAlert:myAlert];
    [self presentModalViewController:openView animated:YES];
}

- (IBAction)onAddVoice:(id)sender {
    [self textFieldShouldReturn:nameTextField];//hide the keyboard
    AudioRecorderViewController *openView = [[AudioRecorderViewController alloc] initWithAlert:myAlert];
    [self presentModalViewController:openView animated:YES];
}

- (IBAction)onDelete:(id)sender {
    [AppDelegate deleteManagedObject:myAlert];
    [self dismissModalViewControllerAnimated:YES];
}
- (BOOL) textFieldShouldReturn:(UITextField*) textField {
    myAlert.name = nameTextField.text;
    [textField resignFirstResponder];
    return YES;
}
@end
